from rest_framework import serializers

from user.models import User, Praise, Comment, Upload


class UserSerializer(serializers.ModelSerializer):
    # 为分组提供数据
    class Meta:
        model = User
        fields = ['id', 'name', 'username', 'email', 'text', "password"]
        read_only_fields = ['id', 'vip', 'username']

        extra_kwargs = {
            'password': {'write_only': True},
        }

    def create(self, validated_data):
        user = super().create(validated_data)
        password = validated_data.get('password')
        if password is not None:
            user.set_password(password)
            user.save()
        return user

    def update(self, instance, validated_data):
        super().update(instance, validated_data)
        password = validated_data.get('password')
        if password is not None:
            instance.set_password(password)
            instance.save()
        return instance


class PraiseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Praise
        fields = "__all__"
        read_only_fields = ['id', ]


class CommentSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Comment
        fields = "__all__"
        read_only_fields = ['id', 'user']
        extra_kwargs = {
            'time': {'required': False},
        }


class UploadSerializer(serializers.ModelSerializer):
    uploader = UserSerializer()
    image_comments = CommentSerializer(many=True)

    class Meta:
        model = Upload
        fields = "__all__"
        read_only_fields = ['id', 'uploader', 'image_praises']


class CommonUploadSerializer(serializers.ModelSerializer):
    uploader = UserSerializer()
    image_comments = CommentSerializer(many=True)

    class Meta:
        model = Upload
        fields = ['id', 'uploader', 'url', 'time', 'image_praises', 'image_comments']
        read_only_fields = ['id', 'uploader']
